<template>
  <el-dialog
    title="NRCT计算"
    :visible.sync="dialogVisible"
    width="1000px"
  >
    <div class="app-container">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
        <el-form-item label="起止时间" prop="created_at">
          <el-date-picker
            v-model="ruleForm.created_at"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="center"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm('ruleForm')">计算</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { nrct } from '@/api/util'
import * as turf from '@turf/turf'
import { mapGetters } from 'vuex'
import { colors } from '@/utils/constant'
import { getGcwdDatas } from '@/api/statistics'
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      nrctData: [],
      ruleForm: {
        serialno: '0202.0007.2027000568',
        created_at: ['2022-05-01 16:10:00', '2022-05-01 22:10:00']
      },
      rules: {
        created_at: [
          { required: true, message: '请选择起止时间', trigger: 'blur' }
        ]
      },
      colors
    }
  },
  computed: {
    ...mapGetters(['project']),
    circlePolygon() {
      const center = [this.project.lng, this.project.lat]
      const radius = 0.1499
      const options = { steps: 100, units: 'kilometers', properties: { foo: 'bar' }}
      return turf.circle(center, radius, options)
    }
  },
  methods: {
    async getGcwdDatas() {
      this.loading = true
      const { data } = await getGcwdDatas(this.ruleForm)
      this.loading = false
      this.$emit('getGcwdDatas', data, this.ruleForm.created_at)
    },
    show() {
      this.dialogVisible = true
    },
    hide() {
      this.dialogVisible = false
    },
    nrct() {
      this.loading = true
      nrct(this.ruleForm).then((res) => {
        this.nrctData = res.data
        this.addLayer()
        this.loading = false
      }).catch((err) => {
        console.log(err)
        this.loading = false
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.getGcwdDatas()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.ruleForm = {
        datetimerange: []
      }
      this.nrctData = []
      this.$emit('resetForm')
    },
    addLayer() {
      const data = this.nrctData
      console.log(data)
      var features = data.map(i => {
        return {
          type: 'Feature',
          properties: {
            value: i.value
          },
          geometry: {
            type: 'Point',
            coordinates: [+i.lng, +i.lat]
          }
        }
      }
      )

      var points = turf.featureCollection(features)
      var interpolate_options = {
        gridType: 'points',
        property: 'value',
        units: 'degrees',
        weight: 1
      }

      var grid = turf.interpolate(points, 0.0001, interpolate_options)
      console.log(grid)

      // 适当降低插值结果的精度便于显示
      grid.features.map((i) => (i.properties.value = i.properties.value.toFixed(4)))

      this.grid = grid.features.map((val) => {
        return {
          lat: val.geometry.coordinates[1],
          lng: val.geometry.coordinates[0],
          awc: val.properties.value
        }
      })

      var isobands_options = {
        zProperty: 'value',
        commonProperties: {
          'fill-opacity': 1
        },
        breaksProperties: colors.map(val => {
          return { fill: val.color }
        })
      }

      let isobands = turf.isobands(
        grid,
        colors.map(val => val.value),
        isobands_options
      )
      isobands = turf.flatten(isobands)

      const features_filter = []
      isobands.features.forEach((layer) => {
        let intersection = null
        try {
          intersection = turf.intersect(layer, this.circlePolygon)
        } catch (e) {
          layer = turf.buffer(layer, 0)
          intersection = turf.intersect(layer, this.circlePolygon)
        }
        if (intersection != null) {
          intersection.properties = layer.properties
          features_filter.push(intersection)
        }
      })
      isobands.features = features_filter

      const geoArr = isobands
      // eslint-disable-next-line no-undef
      const res = L.geoJson(geoArr, { style: this.getFlexStyle })

      console.log(res)

      this.dialogVisible = false
      this.tableData = []
      this.$emit('addLayer', res)
    },
    getFlexStyle(feature) {
      return {
        weight: 1,
        opacity: 0,
        color: '#fff',
        fillOpacity: 0.6,
        fillColor: feature.properties.fill }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
